<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <title>indexDB测试</title>
        <!-- 无法访问 -->
        <script src="https://fastly.jsdelivr.net/npm/idb@8/build/umd.js"></script>
        <style scoped>
            body {
                margin: 0;
                width: 100%;
                height: 100%;
                background-color: aquamarine;
            }

            .btn-box {
                display: flex;
                align-items: center;
                gap: 20px;
                margin: 20px 0;
            }
            
            .primary {
                padding: 5px 10px;
                background-color: cornflowerblue;
                color: white;
            }

            .danger {
                padding: 5px 10px;
                background-color: crimson;
                color: white;
            }

            .box {
                padding: 20px;
                border-radius: 4px;
            }
        </style>
    </head>

    <body>
        <h1 id="title">用户列表</h1>
        <div class="btn-box">
            <button class="primary" id="add">新增</button>
        </div>
        <ul id="user" class="box"></ul>
    </body>

    <script type="module">
        const STORE_PERMISSION = 'readwrite'
        const STORE_NAME = 'users'
        const DB_NAME = 'user_db_1'
        let titleDom = document.getElementById('title')
        let userDom = document.getElementById('user')
        let addBtnDom = document.getElementById('add')
        let db
        init()

        async function init() {
           try {
                db = await idb.openDB(DB_NAME, 1, {
                    upgrade(db) {
                        // Create a store of objects
                        const store = db.createObjectStore(STORE_NAME, {
                            // The 'id' property of the object will be the key.
                            keyPath: 'phone',
                            // If it isn't explicitly set, create a value by auto incrementing.
                            // autoIncrement: true,
                        });
                        // Create an index on the 'date' property of the objects.
                        store.createIndex('date', 'date');
                    },
                });
                getUserList()
           } catch (error) {
            console.log('--error--', error)
           }
        }

        async function getUserList() {
            try {
                const tx = db.transaction(STORE_NAME, STORE_PERMISSION)
                const userStore = tx.objectStore(STORE_NAME)
                const userList = await userStore.getAll()

                if (!userList || !userList.length) {
                    userDom.appendChild(document.createElement('li')).innerText = '暂无数据~'
                    return
                }

                // 清除DOM子元素
                while (userDom.lastChild) {
                    userDom.removeChild(userDom.lastChild);
                }

                userList.forEach((userObj) => {
                    userDom.appendChild(document.createElement('li')).innerText = `姓名：${userObj.name} 手机：${userObj.phone}`
                })
            } catch (error) {
                console.log('--getUserList error--', error)
            }
        }

        async function addUser() {
            const userName = prompt('请输入用户名')
            const userPhone = prompt('请输入用户手机号')
            const tx = db.transaction(STORE_NAME, STORE_PERMISSION)
            const userStore = tx.objectStore(STORE_NAME)

            try {
                await userStore.add({ name: userName, phone: userPhone})
                await getUserList()
            } catch (error) {
                if (error.name === 'ConstraintError') {
                    alert('用户已存在，请重新输入!')
                } else {
                    throw error
                }
            }
        }

        addBtnDom.addEventListener('click', async () => {
            addUser()
        })

    </script>
</html>